#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int a,b;

int exgcd(int a,int b,int &x,int& y){
	if(b==0){
		x=1,y=0;
		return a;
	}
	int r=exgcd(b,a%b,y,x);
	y=y-(a/b)*x;
	return r;	
}

int inv(int a,int b){
	int x,y,d;
	d=exgcd(a,b,x,y);
	return d==1?(x+b)%b:-1;
}

int main(){
	cin>>a>>b;
	int ans = inv(a,b);
	cout<<ans<<endl;
	return 0;
}
